package com.lagou.edu.utils;

import com.lagou.edu.exception.InitException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component("connectionUtils")
public class ConnectionUtils {

    private DataSource dataSource;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private final ThreadLocal<Connection> CONNECTION_HOLDER = ThreadLocal.withInitial(() -> {
        try {
            return this.dataSource.getConnection();
        } catch (SQLException e) {
            throw new InitException(e);
        }
    });

    public Connection getConnection() {
        return CONNECTION_HOLDER.get();
    }

}
